## Load packages ----
pacman::p_load(rio, tidyverse, broom, ggplot2, gridExtra, hrbrthemes, stringi, tufte,
               summarytools, jtools, ggthemes, cjoint, data.table, ChoiceModelR, cregg,
               viridis, extrafont, survey, lubridate, rstatix, tableone, knitr, kableExtra, MatchIt,
               ggpubr, cowplot, vctrs, qpdf, ggpubr)

## Load and clean data ----

# load data
conjoint_data <- read_csv("data_processed.csv")

# string variables to be converted to factors
factor_vars <- c("age", "gender", "residence", "occ", "lang", "ctry.rival", "ctry.race", "country", 
                 "ctry.race.rival", "origin", "majority", "chauv_bin")

# final recode
conjoint_data <- conjoint_data %>%
  mutate(
    country = tolower(country),
    across(all_of(factor_vars), as.factor),
    across(all_of(c("age", "gender", "lang")), ~fct_rev(.x)),
    residence = factor(residence, levels = c("Residence: 5 years", "Residence: 10 years", "Residence: 15 years")),
    occ = factor(occ, levels=c("Occupation: Unemployed", "Occupation: Cleaner", "Occupation: Farmer", 
                               "Occupation: Accountant", "Occupation: Teacher", "Occupation: Doctor")),
    ctry.rival = factor(ctry.rival, levels = c("Country of origin: Non-rival", "Country of origin: Rival")),
    majority = factor(majority, levels=c("Minority respondents", "Majority respondents")),
    origin = fct_rev(origin),
    ctry.race = factor(ctry.race, levels = c("Country of origin: Similar majority race/culture",
                                             "Country of origin: Different majority race/culture")),
    ctry.race.rival = factor(ctry.race.rival, levels = c(
      "Country of origin: Similar majority race/culture + Non-rival", 
      "Country of origin: Similar majority race/culture + Rival", 
      "Country of origin: Different majority race/culture + Non-rival",
      "Country of origin: Different majority race/culture + Rival"))) 

# create folders for figures and tables
if (file.exists('figures/')){
} else {
  dir.create('figures/')
}

if (file.exists('figures/pdf/')){
} else {
  dir.create('figures/pdf/')
}

if (file.exists('figures/png/')){
} else {
  dir.create('figures/png/')
}

if (file.exists('tables/')){
} else {
  dir.create('tables/')
}

# labels for interaction effect figures
indicators <- c("Country of origin: Different majority race/culture + Rival",
                "Country of origin: Different majority race/culture + Non-rival",
                "Country of origin: Similar majority race/culture + Rival",
                "Country of origin: Similar majority race/culture + Non-rival"
                )

indicators_linebreaks <- c("Country of origin:\nDifferent race/culture + Rival",
                           "Country of origin:\nDifferent race/culture + Non-rival",
                           "Country of origin:\nSimilar race/culture + Rival", 
                           "Country of origin:\nSimilar race/culture + Non-rival")

# countries with Russia, Ukraine, China, and Japan conditions
countries_rucj <- c(
  'canada',
  'italy',
  'australia',
  'us',
  'spain',
  'netherlands',
  'uk',
  'italy',
  'germany',
  'france',
  'hungary',
  'sweden',
  'brazil',
  'poland')

# countries with Russia, Ukraine, China, and Japan conditions (reduced)
countries_rucj_reduced <- c(
  'canada',
  'italy',
  'us',
  'spain',
  'netherlands',
  'uk',
  'italy',
  'germany',
  'france',
  'hungary',
  'sweden',
  'poland')

exclude_countries_vsurvey <- c("south africa", "hungary", "peru", "philippines", "turkey", "india")

## Conjoint analysis function ----

# function to run conjoint analysis and return (1) plot (2) model, and (3) table.
# args: 
# data: data frame, covariates: focal covariates realted to rivalry status and race/culture), 
# by - optional subgroup variable, minimal - optional minimal plot with results only for focal covariates,
# tab_cap - optional table caption, optonal tab_line_sep - table line separator pattern, 
# rus_chi - optional filter for returning table with only Russia, Ukraine, China, and Japan marginal means

cj_funct <- function(data, covariates, by = NULL, minimal = FALSE, tab_cap = NULL, tab_line_sep = NULL, rus_chi = FALSE) {
  
  if(is.null(by)) {
    
    formula <- as.formula(paste0("selected ~ age + gender + residence + occ + lang + ", paste(covariates, collapse=" + ")))
    model <- cj(data, formula, id = ~ ResponseId, estimate = "mm", family = stats.binomial())
  
    if(minimal == FALSE) {
      plot <- ggplot(subset(model, !is.na(estimate)), aes(x=level, y=estimate, ymin=lower, ymax=upper))
      
    } else if(minimal == TRUE) {
      
      plot <- ggplot(subset(model, feature %in% covariates & !is.na(estimate)), 
             aes(x=level, y=estimate, ymin=lower, ymax=upper))
      
    }
    
    plot <- plot + theme_minimal(base_size = 14) + coord_flip() +  theme(legend.position = "none") 
    
    if(rus_chi == FALSE) {
      table <- model %>% dplyr::filter(!is.na(estimate))
    } else if (rus_chi == TRUE) {
      table <- model %>% dplyr::filter(!is.na(estimate) & level %in% c("China", "Japan", "Russia", "Ukraine"))
    }
    
    table <- table %>%
      select(-c(feature, outcome, statistic, p)) %>%
      kbl(digits=3, caption = tab_cap, format="latex", booktabs=TRUE, linesep = tab_line_sep,
          col.names = c("Attribute", "Estimate", "St.Err.", "Z", "CI Lower", "CI Upper")) %>% 
      column_spec(1, latex_column_spec = "l") %>%
      column_spec(2:ncol(table), latex_column_spec = "c") %>%
      kable_styling(latex_options = "scale_down", full_width = F)
  
  } else {
    
    formula <- as.formula(paste0("selected ~ age + gender + residence + occ + lang + ", paste(covariates, collapse=" + ")))
    model <- cj(data, formula, id = ~ ResponseId, estimate = "mm", family = stats.binomial(), by = as.formula(paste0("~",by)))
    by_length <- nrow(data %>% summarise(unique(na.omit(get(by)))))
    shapes <- c(21,16,24,18)[1:by_length]
    
    if(minimal == FALSE) {
      plot <- ggplot(subset(model, !is.na(estimate)), 
                     aes(x=level, y=estimate, ymin=lower, ymax=upper, shape = get(by)))
      
    } else if(minimal == TRUE) {
      plot <- ggplot(subset(model, feature %in% covariates & !is.na(estimate)), 
                     aes(x=level, y=estimate, ymin=lower, ymax=upper, shape = get(by)))
      
    }
    
    plot <- plot + theme_minimal(base_size = 14) + 
      coord_flip() +
      theme(legend.position="bottom", legend.title=element_blank(),
            legend.text=element_text(size=8),
            legend.box.background = element_rect(colour = "black", linewidth=0.1)) +
      scale_shape_manual(values=shapes) +
      theme(legend.text = element_text(margin = margin(l = 0)),
            legend.margin = margin(c(.1, .2, .1, .1), unit = "cm"))

    if(rus_chi == FALSE) {
      table <- model %>% dplyr::filter(!is.na(estimate))
    } else if (rus_chi == TRUE) {
      table <- model %>% dplyr::filter(!is.na(estimate) & level %in% c("China", "Japan", "Russia", "Ukraine"))
    }
    
    table <- table %>%
      select(-c(feature, outcome, statistic, p, tail(names(.), 1))) %>%
      kbl(digits=3, caption = tab_cap, format="latex", booktabs=TRUE, linesep = tab_line_sep,
          col.names = c("Subgroup", "Attribute", "Estimate", "St.Err.", "Z", "CI Lower", "CI Upper")) %>% 
      column_spec(1:2, latex_column_spec = "l") %>%
      column_spec(3:ncol(table), latex_column_spec = "c") %>%
      kable_styling(latex_options = "scale_down", full_width = F)
    
  }
  
  plot <- plot + geom_hline(yintercept=0.5, color=gray(1/2), lty=2) +
    geom_point(size=2, position = position_dodge(.7)) +
    geom_linerange(linewidth=.5, position = position_dodge(.7)) +
    ylab("        Marginal Mean") +
    theme(axis.title.y = element_blank(),
          axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 0, l = 10)),
          axis.title = element_text(size=10)) +
    facet_grid(factor(feature, levels=c("age", "gender", "residence", "lang", "occ", covariates))~., scales="free", space="free") +
    theme(strip.text.y = element_blank(), axis.text = element_text(size = 10),
          plot.background = element_rect(fill = 'white'))
  
  return(list(plot, model, table))

}

## Main figures ----

# captions for conjoint result tables
tab_captions = c("Table I. Conjoint results: Race and rivalry (corresponds to Figure 1)",
                 "Table II. Conjoint results: Race and rivalry interaction (corresponds to Figure 2)",
                 "Table III. Conjoint results: War in Ukraine (corresponds to Figure 3)",
                 "Table IV. Conjoint results:  Rivalry and racial/cultural similarity by respondents' majority status (corresponds to Figure 4)",
                 "Table V. Conjoint results:  Rivalry and racial/cultural similarity by respondents' sense of national superiority (corresponds to Figure 5)",
                 "Table A.I. Conjoint results:  Rivalry and racial/cultural similarity; countries without Russia, Ukraine, China, Japan conditions (corresponds to Figure A1)",
                 "Table A.IV. Conjoint results: War in Ukraine; matched sample (corresponds to Figure A4)",
                 "Table A.VIa. Rivalry and racial/cultural similarity; reduced country sample (corresponds to Figure A6a)",
                 "Table A.VIb. Rivalry and racial/cultural similarity interaction; reduced country sample (corresponds to Figure A6b)",
                 "Table A.VIc. Rivalry and racial/cultural similarity by respondents' majority status; reduced country sample (corresponds to Figure A6c)",
                 "Table A.VII. Rivalry and racial/cultural similarity by respondents' majority status; survey countries without the Russia-Ukraine pair",
                 "Table A.VIII. Rivalry and racial/cultural similarity by respondents' sense of national superiority; survey countries without the Russia-Ukraine pair"
                 )

# captions for conjoint result figures; short version (for APSR production purposes)
fig_captions = c("Figure 1",
                 "Figure 2",
                 "Figure 3",
                 "Figure 4",
                 "Figure 5",
                 "Figure A1",
                 "Figure A3",
                 "Figure A4",
                 "Figure A6a",
                 "Figure A6b",
                 "Figure A6c",
                 "Figure A7",
                 "Figure A8"
                 )

# captions for conjoint result figures; long version (currently only used in text)
fig_captions_long = c("Figure 1. Effects of rivalry and perceived racial/cultural similarity on probability of being granted permanent resident status",
                 "Figure 2. Interaction effects of rivalry status and perceived racial/cultural similarity on probability of being granted permanent residence status",
                 "Figure 3. Preference for Russian and Ukrainian immigrants before and after Russian invasion of Ukraine",
                 "Figure 4. Effects of rivalry and racial/cultural similarity by respondents' majority status",
                 "Figure 5. Effects of rivalry and racial/cultural similarity by respondents' perceptions of national superiority",
                 "Figure A1. Effects of rivalry and racial/cultural similarity; survey countries without Russia-Ukraine condition",
                 "Figure A3. Preference for immigrant countries of origin by survey country",
                 "Figure A4. Preference for Russian and Ukrainian immigrants before and after Russian invasion of Ukraine; matched sample",
                 "Figure A6a. Rivalry and racial/cultural similarity effects; reduced country sample",
                 "Figure A6b. Rivalry and racial/cultural similarity interaction effects; reduced country sample",
                 "Figure A6c. Rivalry and racial/cultural similarity effects by respondents' majority satus; reduced country sample",
                 "Figure A7. Rivalry and racial/cultural similarity effects by respondents' majority status; survey countries without Russia-Ukraine condition",
                 "Figure A8. Rivalry and racial/cultural similarity effects by respondents' perceptions of national superiority; survey countries without Russia-Ukraine condition"
)


## FIGURE 1: Race and rivalry

# call conjoint function
cj_race_rival <- cj_funct(conjoint_data, c("ctry.race", "ctry.rival"), tab_cap = tab_captions[1])

# plot conjoint results
p <- cj_race_rival[[1]] + 
  ggtitle(str_wrap(fig_captions[1], 
                   width = 100)) + theme(plot.title = element_text(size = 10, hjust = 0.5, margin=margin(0,0,30,0)),
                                         plot.title.position = "plot")

ggsave("figures/png/fig1_race_rival.png", p, dpi=600, width=6.5, height=6, units='in')
ggsave("figures/pdf/fig1_race_rival.pdf", p, dpi=600, width=6.5, height=6, units='in')

# generate results table
cj_race_rival[[3]] %>% save_kable("tables/SuppTable1.pdf", 
                                  latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                  density = 300)

## FIGURE 2: Race/rivalry interaction

# call conjoint function
cj_raceXrival <- cj_funct(conjoint_data, "ctry.race.rival", minimal = TRUE, tab_cap = tab_captions[2])

# plot conjoint results
p <- cj_raceXrival[[1]] +
  ylim(.425,.575) + scale_x_discrete(breaks = indicators, labels = indicators_linebreaks) + 
  ggtitle(str_wrap(fig_captions[2], 
                   width = 110)) +
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), plot.title.position = "plot")

ggsave("figures/png/fig2_raceXrival.png", p, dpi=600, width=6, height=3, units='in')
ggsave("figures/pdf/fig2_raceXrival.pdf", p, dpi=600, width=6, height=3, units='in')

# generate results table
cj_raceXrival[[3]] %>% save_kable("tables/SuppTable2.pdf", 
                                  latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                  density = 300)

## FIGURE 3: War effect

# subset data for war analysis, recode variables
conjoint_data_war <- conjoint_data %>% dplyr::filter(country %in% countries_rucj_reduced & bef_after_war <=6) %>%
  mutate(war_2d = case_when(
    bef_after_war < 0 ~ "Up to 2 days before war",
    bef_after_war %in% c(0, 1) ~ "0-1 days of war",
    bef_after_war %in% c(2, 3) ~ "2-3 days of war",
    bef_after_war %in% c(4, 5) ~ "4-5 days of war",
    bef_after_war == 6 ~ NA_character_),
    war_2d = factor(war_2d, levels = c("4-5 days of war", "2-3 days of war", "0-1 days of war", 
                                       "Up to 2 days before war")))

# call conjoint function
cj_war <- cj_funct(conjoint_data_war, "origin", by = "war_2d", minimal = TRUE, tab_cap = tab_captions[3], 
                   tab_line_sep = c('', '', '', '\\addlinespace'), rus_chi = TRUE)

# plot conjoint results  
p <- cj_war[[1]] + guides(shape = guide_legend(theme = theme(legend.text = element_text(size = 8)), byrow=TRUE, 
                                               reverse = TRUE)) + 
  ggtitle(str_wrap(fig_captions[3], 
                   width = 90)) + theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
                                        plot.title.position = "plot")

ggsave("figures/png/fig3_war.png", p, dpi=600, width=6, height=5, units='in')
ggsave("figures/pdf/fig3_war.pdf", p, dpi=600, width=6, height=5, units='in')

# generate results table
cj_war[[3]] %>% save_kable("tables/SuppTable3.pdf", 
                           latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                           density = 300)


## FIGURE 4: Race, rivalry (no interaction) w. respondent's majority / minority status

# call conjoint function
cj_race_rival_maj <- cj_funct(conjoint_data, c("ctry.race", "ctry.rival"), by = "majority", minimal = TRUE,
                              tab_cap = tab_captions[4], tab_line_sep = c(rep("", 20),"\\addlinespace"))

# plot conjoint results 
p <- cj_race_rival_maj[[1]] + ylim(.425,.575) + scale_x_discrete(
  breaks =c(
    "Country of origin: Different majority race/culture",
    "Country of origin: Similar majority race/culture",
    "Country of origin: Rival",
    "Country of origin: Non-rival"), 
  labels = c(
    "Country of origin:\n Different majority race/culture",
    "Country of origin:\n Similar majority race/culture",
    "Country of origin:\n Rival",
    "Country of origin:\n Non-rival"
  )) + 
  guides(shape = guide_legend(reverse=TRUE, theme = theme(legend.text = element_text(size = 9)), byrow=TRUE)) + 
  ggtitle(str_wrap(fig_captions[4], 
                   width = 90)) + theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
                                        plot.title.position = "plot")

ggsave("figures/png/fig4_race_rival_maj.png", p, dpi=600, width=6, height=5, units='in')
ggsave("figures/pdf/fig4_race_rival_maj.pdf", p, dpi=600, width=6, height=5, units='in')

# generate results table
cj_race_rival_maj[[3]] %>% save_kable("tables/SuppTable4.pdf",
                                      latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                      density = 300)


## FIGURE 5: Race, rivalry (no interaction) w. chauvinism

# call conjoint function
cj_race_rival_chauv <- cj_funct(conjoint_data, c("ctry.race", "ctry.rival"), by = "chauv_bin", minimal = TRUE,
                                tab_cap = tab_captions[5], tab_line_sep = c(rep("", 20),"\\addlinespace"))

# plot conjoint results 
p <- cj_race_rival_chauv[[1]] + theme(legend.position="bottom", legend.title=element_blank(),
          legend.text=element_text(size=10),
          legend.box.background = element_rect(colour = "black", linewidth=0.1)) +
  scale_x_discrete(
    breaks =c(
      "Country of origin: Different majority race/culture",
      "Country of origin: Similar majority race/culture",
      "Country of origin: Rival",
      "Country of origin: Non-rival"), 
    labels = c(
      "Country of origin:\n Different majority race/culture",
      "Country of origin:\n Similar majority race/culture",
      "Country of origin:\n Rival",
      "Country of origin:\n Non-rival"
    )) + 
  guides(shape = guide_legend(reverse=TRUE, theme = theme(legend.text = element_text(size = 9)), byrow=TRUE)) + 
  ggtitle(str_wrap(fig_captions[5], 
                   width = 100)) + theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
                                        plot.title.position = "plot")

ggsave("figures/png/fig5_race_rival_chauv.png", p, dpi=600, width=6.5, height=5, units='in')
ggsave("figures/pdf/fig5_race_rival_chauv.pdf", p, dpi=600, width=6.5, height=5, units='in')

# generate results table
cj_race_rival_chauv[[3]] %>% save_kable("tables/SuppTable5.pdf", 
                                        latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                        density = 300)


## Appendix figures ----

## FIGURE A1: Race and rivalry: countries without Russia, Ukraine, China, Japan conditions (i.e., non-RUCJ)

# subset data
conjoint_data_nonrucj <- conjoint_data %>% filter(!country %in% countries_rucj)

# call conjoint function
cj_race_rival_nonrucj <- cj_funct(conjoint_data_nonrucj, c("ctry.race", "ctry.rival"),
                                  tab_cap = tab_captions[6])

# plot conjoint results (appendix figure titles in text only)
p <- cj_race_rival_nonrucj[[1]] + 
  #ggtitle(str_wrap(fig_captions_long[6], width = 100)) + 
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
        plot.title.position = "plot")

ggsave("figures/png/figA1_race_rival_nonrucj.png", p, dpi=600, width=6.5, height=6, units='in')
ggsave("figures/pdf/figA1_race_rival_nonrucj.pdf", p, dpi=600, width=6.5, height=6, units='in')

# generate results table
cj_race_rival_nonrucj[[3]] %>% save_kable("tables/SuppTableA1.pdf", 
                                          latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                          density = 300)


## FIGURE A4: Country figures

# create folder for country figures
if (file.exists('figures/by_country/')){
} else {
  dir.create('figures/by_country/')
}

# loop through all the countries in alphabetical order and generate plots

plist = sapply(sort(unique(conjoint_data$country)), function(col) {
  if (col %in% c('us','uk')){ 
    title = str_to_upper(col)
  } else {
    title = str_to_title(col)
  }
  cj_country <- cj_funct(conjoint_data[conjoint_data$country==col,], c("origin"), by = "ctry.rival", minimal = TRUE, 
                         tab_cap = paste0("Table A.III: ", title))
  p <- cj_country[[1]] + theme(plot.title = element_text(hjust = 0.5)) + ggtitle(title) + ylim(.3,.7)
  cj_country[[3]] %>% save_kable(paste0("tables/SuppTableA3_", col, ".pdf"), 
                                          latex_header_includes = c("\\usepackage[labelformat = empty, skip=0pt]{caption}"),
                                          density = 300)
  return(p)
  }, simplify=FALSE)

# aggreagte plots to 8 per page (appendix figure titles in text only)
plist_sub <- plist[c(1:8)]
g <- arrangeGrob(grobs = plist_sub, ncol = 2 #, top = textGrob(fig_captions_long[7], gp=gpar(fontsize=18))
                 )

ggsave("figures/png/figA3.1-countries.png", g, dpi=600, width=8.5, height=11, units='in') 
ggsave("figures/pdf/figA3.1-countries.pdf", g, dpi=600, width=8.5, height=11, units='in') 

plist_sub <- plist[c(9:16)]
g <- arrangeGrob(grobs = plist_sub, ncol = 2)
ggsave("figures/png/figA3.2-countries.png", g, dpi=600, width=8.5, height=11, units='in') 
ggsave("figures/pdf/figA3.2-countries.pdf", g, dpi=600, width=8.5, height=11, units='in') 

plist_sub <- plist[c(17:22)]
g <- arrangeGrob(grobs = plist_sub, ncol = 2)
ggsave("figures/png/figA3.3-countries.png", g, dpi=600, width=8.5, height=11, units='in') 
ggsave("figures/pdf/figA3.3-countries.pdf", g, dpi=600, width=8.5, height=11, units='in') 

## Balanced sample analysis and Figure A4 ----

# load data with only the relevant columns
df = read_csv("data_test.csv")
df <- df %>% select(ResponseId, EndDate, age, gender, ed_postsec, income_quintile, citizen, working, marital_status,
                    duration, country)

# recode variables as binary
df.tests <- df %>%
  mutate(
    survdate = as.Date(df$EndDate, format="%Y-%m-%d"),
    afterwar = as.logical(case_when(
      survdate < as.Date('2022-02-24') & survdate >= as.Date('2022-02-22') ~ 0,
      survdate >= as.Date('2022-02-24') & survdate <= as.Date('2022-03-01') ~ 1
    )),
    age = recode(age, "80+" = "80") %>% as.numeric(),
    gender = factor(gender),
    ed_postsec = factor(ed_postsec) %>% fct_recode("<=BA" = "0", ">BA" = "1"),
    citizen = factor(citizen) %>% fct_recode("Citizen" = "Yes", "Non-Citizen" = "No"),
    working2 = factor(working) %>% fct_recode("Working" = "Working full time", "Working" = "Working part time",
                                              "Not working" = "In school",
                                              "Not working" = "Keeping house",
                                              "Not working" = "Other",
                                              "Not working" = "Retired",
                                              "Not working" = "Unemployed, laid off, looking for work",
                                              "Not working" = "With a job, but not at work because of temporary illness, vacation, strike",
                                              "Not working" = "No answer"),
    married = factor(marital_status) %>% fct_recode("Married" = "Married or in a domestic partnership",
                                                    "Not married" = "Divorced",
                                                    "Not married" = "Separated",
                                                    "Not married" = "Widowed",
                                                    "Not married" = "Single (never married)"
    )
  ) %>% 
  filter(
    gender %in% c("Man", "Woman"),
    tolower(country) %in% countries_rucj_reduced,
    if_all(c("afterwar", "age", "duration", "gender", "ed_postsec", "income_quintile", "citizen", "working2", "married"), 
           negate(is.na))
  )

# compare unmatched sample pre- and post-war
table1 <- CreateTableOne(vars = c('age', 'duration', 'gender', 'ed_postsec', 'income_quintile', 'citizen', 'working2', 'married'), 
                         data = df.tests, 
                         factorVars = c('gender','ed_postsec','citizen','working2','married'), 
                         strata = 'afterwar')
table1 <- print(table1, 
                printToggle = FALSE, 
                noSpaces = TRUE)
table1 %>% kbl(caption = 'Table 1: Comparison of unmatched samples') %>% kable_styling()


## Rebalanced sample analysis

# prefrom optimal matching on four demographic variables for pre- and post-war sample
set.seed(1234)
match.it <- matchit(afterwar ~ age + gender + working2 + married, data = df.tests, method="optimal", ratio=2)

# display matching results
summary(match.it)

prematch <- summary(match.it)[[3]]
postmatch <- summary(match.it)[[4]]

kable(prematch, digits=2, caption = "<center><b>Full sample</b></center>") %>% kable_styling()
kable(postmatch, digits=2, caption = "<center><b>Matched sample</b></center>") %>% kable_styling()

# generate matched sample
war.sample.matched <- match.data(match.it)[1:ncol(df.tests)]

conjoint_data_war_matched <- conjoint_data_war %>% filter(ResponseId %in% war.sample.matched$ResponseId) %>%
  mutate(war_2d = factor(war_2d, levels = c("4-5 days of war", "2-3 days of war", "0-1 days of war", 
                                            "Up to 2 days before war")))

# call conjoint function
cj_matched <- cj_funct(conjoint_data_war_matched, "origin", by = "war_2d", minimal = TRUE,
                       tab_cap = tab_captions[7], tab_line_sep = c('', '', '', '\\addlinespace'), rus_chi = TRUE)

# plot conjoint results (appendix figure titles in text only)
p <- cj_matched[[1]] + guides(shape = guide_legend(theme = theme(legend.text = element_text(size = 8)), byrow=TRUE, 
                                               reverse = TRUE)) + 
  #ggtitle(str_wrap(fig_captions_long[8], width = 100)) + 
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
                                         plot.title.position = "plot")

ggsave("figures/png/figA4_matched.png", p, dpi=600, width=6.5, height=6, units='in')
ggsave("figures/pdf/figA4_matched.pdf", p, dpi=600, width=6.5, height=6, units='in')

# generate results table
cj_matched[[3]] %>% save_kable("tables/SuppTableA4.pdf", 
                               latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                               density = 300)

## Appendix figures continued ----


## FIGURE A6a: Race and rivalry; excluding countries for which assumptions weren't validated in supplementary survey 
## (South Africa, Hungary, Peru, Philippines, Turkey, and India)

# call conjoint function
cj_race_rival_red <- cj_funct(subset(conjoint_data, !(country %in% exclude_countries_vsurvey)), c("ctry.race", "ctry.rival"), 
                                 tab_cap = tab_captions[8])

# plot conjoint results (appendix figure titles in text only)
p <- cj_race_rival_red[[1]] + 
  # ggtitle(str_wrap(fig_captions_long[9], width = 100)) + 
  theme(plot.title = element_text(size = 10, hjust = 0.5, margin=margin(0,0,30,0)),
        plot.title.position = "plot")

ggsave("figures/png/figA6a_race_rival.png", p, dpi=600, width=6.5, height=6, units='in')
ggsave("figures/pdf/figA6a_race_rival.pdf", p, dpi=600, width=6.5, height=6, units='in')

# generate results table
cj_race_rival_red[[3]] %>% save_kable("tables/SuppTableA6a.pdf", 
                                  latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                  density = 300)

## FIGURE A6b: Race/rivalry interaction; excluding countries for which assumptions weren't validated in supplementary survey 
## (South Africa, Hungary, Peru, Philippines, Turkey, and India)

# call conjoint function
cj_raceXrival_red <- cj_funct(subset(conjoint_data, !(country %in% exclude_countries_vsurvey)), "ctry.race.rival", 
                          minimal = TRUE, tab_cap = tab_captions[9])

# plot conjoint results (appendix figure titles in text only)
p <- cj_raceXrival_red[[1]] +
  ylim(.425,.575) + scale_x_discrete(breaks = indicators, labels = indicators_linebreaks) + 
  #ggtitle(str_wrap(fig_captions_long[10], width = 110)) +
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), plot.title.position = "plot")

ggsave("figures/png/figA6b_raceXrival.png", p, dpi=600, width=6, height=3, units='in')
ggsave("figures/pdf/figA6b_raceXrival.pdf", p, dpi=600, width=6, height=3, units='in')

# generate results table
cj_raceXrival_red[[3]] %>% save_kable("tables/SuppTableA6b.pdf", 
                                  latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                  density = 300)

## FIGURE A6c: Race/rivalry w. respondent's majority / minority status; excluding countries for which assumptions weren't validated in supplementary survey 
## (South Africa, Hungary, Peru, Philippines, Turkey, and India)

# call conjoint function
cj_race_rival_maj_red <- cj_funct(subset(conjoint_data, !(country %in% exclude_countries_vsurvey)), c("ctry.race", "ctry.rival"), 
                          by = "majority", minimal = TRUE, tab_cap = tab_captions[10], 
                          tab_line_sep = c(rep("", 20),"\\addlinespace"))

# plot conjoint results (appendix figure titles in text only)
p <- cj_race_rival_maj_red[[1]] + ylim(.425,.575) + scale_x_discrete(
  breaks =c(
    "Country of origin: Different majority race/culture",
    "Country of origin: Similar majority race/culture",
    "Country of origin: Rival",
    "Country of origin: Non-rival"), 
  labels = c(
    "Country of origin:\n Different majority race/culture",
    "Country of origin:\n Similar majority race/culture",
    "Country of origin:\n Rival",
    "Country of origin:\n Non-rival"
  )) + 
  guides(shape = guide_legend(reverse=TRUE, theme = theme(legend.text = element_text(size = 9)), byrow=TRUE)) + 
  # ggtitle(str_wrap(fig_captions_long[11],width = 110)) +
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), plot.title.position = "plot")

ggsave("figures/png/figA6c_raceXrival_maj.png", p, dpi=600, width=6, height=5, units='in')
ggsave("figures/pdf/figA6c_raceXrival_maj.pdf", p, dpi=600, width=6, height=5, units='in')

# generate results table
cj_race_rival_maj_red[[3]] %>% save_kable("tables/SuppTableA6c.pdf", 
                                  latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                  density = 300)


## FIGURE A7: Race, rivalry (no interaction) w. respondent's majority / minority status; 
## countries without Russia, Ukraine, China, Japan conditions (i.e., non-RUCJ)

# call conjoint function
cj_race_rival_maj_nonrujc <- cj_funct(conjoint_data_nonrucj, c("ctry.race", "ctry.rival"), by = "majority", minimal = TRUE,
                              tab_cap = tab_captions[11], tab_line_sep = c(rep("", 20),"\\addlinespace"))

# plot conjoint results (appendix figure titles in text only)
p <- cj_race_rival_maj_nonrujc[[1]] + ylim(.425,.575) + scale_x_discrete(
  breaks =c(
    "Country of origin: Different majority race/culture",
    "Country of origin: Similar majority race/culture",
    "Country of origin: Rival",
    "Country of origin: Non-rival"), 
  labels = c(
    "Country of origin:\n Different majority race/culture",
    "Country of origin:\n Similar majority race/culture",
    "Country of origin:\n Rival",
    "Country of origin:\n Non-rival"
  )) + 
  guides(shape = guide_legend(reverse=TRUE, theme = theme(legend.text = element_text(size = 9)), byrow=TRUE)) + 
  #ggtitle(str_wrap(fig_captions_long[12], width = 90)) + 
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
                                        plot.title.position = "plot")

ggsave("figures/png/figA7_race_rival_maj.png", p, dpi=600, width=6, height=5, units='in')
ggsave("figures/pdf/figA7_race_rival_maj.pdf", p, dpi=600, width=6, height=5, units='in')

# generate results table
cj_race_rival_maj_nonrujc[[3]] %>% save_kable("tables/SuppTableA7.pdf",
                                      latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                      density = 300)


## FIGURE A8: Race, rivalry (no interaction) w. chauvinism
## countries without Russia, Ukraine, China, Japan conditions (i.e., non-RUCJ)

# call conjoint function
cj_race_rival_chauv_nonrujc <- cj_funct(conjoint_data_nonrucj, c("ctry.race", "ctry.rival"), by = "chauv_bin", minimal = TRUE,
                                tab_cap = tab_captions[12], tab_line_sep = c(rep("", 20),"\\addlinespace"))

# plot conjoint results (appendix figure titles in text only)
p <- cj_race_rival_chauv_nonrujc[[1]] + theme(legend.position="bottom", legend.title=element_blank(),
                                      legend.text=element_text(size=10),
                                      legend.box.background = element_rect(colour = "black", linewidth=0.1)) +
  scale_x_discrete(
    breaks =c(
      "Country of origin: Different majority race/culture",
      "Country of origin: Similar majority race/culture",
      "Country of origin: Rival",
      "Country of origin: Non-rival"), 
    labels = c(
      "Country of origin:\n Different majority race/culture",
      "Country of origin:\n Similar majority race/culture",
      "Country of origin:\n Rival",
      "Country of origin:\n Non-rival"
    )) + 
  guides(shape = guide_legend(reverse=TRUE, theme = theme(legend.text = element_text(size = 9)), byrow=TRUE)) + 
  #ggtitle(str_wrap(fig_captions_long[13], width = 100)) + 
  theme(plot.title = element_text(size = 9, hjust = 0.5, margin=margin(0,0,30,0)), 
                                         plot.title.position = "plot")

ggsave("figures/png/figA8_race_rival_chauv.png", p, dpi=600, width=6.5, height=5, units='in')
ggsave("figures/pdf/figA8_race_rival_chauv.pdf", p, dpi=600, width=6.5, height=5, units='in')

# generate results table
cj_race_rival_chauv_nonrujc[[3]] %>% save_kable("tables/SuppTableA8.pdf", 
                                        latex_header_includes = c("\\usepackage[labelformat = empty, skip=-12pt]{caption}"),
                                        density = 300)

## Aggregate PDFs ----

# gather all figure pdfs into a single pdf file
fig_pdfs_details <- file.info(list.files(path = "figures/pdf/", pattern = "\\.pdf$", ignore.case = TRUE))
fig_pdfs_details = fig_pdfs_details[with(fig_pdfs_details, order(as.POSIXct(mtime))), ]
fig_pdfs = paste0(paste0("figures/pdf/", rownames(fig_pdfs_details)))

pdf_combine(input = fig_pdfs, output = "figures_all.pdf")

# gather all table pdfs into a single pdf file
table_pdfs_details <- file.info(list.files(path = "tables/", pattern = "\\.pdf$", ignore.case = TRUE))
table_pdfs_details = table_pdfs_details[with(table_pdfs_details, order(as.POSIXct(mtime))), ]
table_pdfs = paste0(paste0("tables/", rownames(table_pdfs_details)))

pdf_combine(input = table_pdfs, output = "tables_all.pdf")
